package com.cyx.exercise;

import com.cyx.exercise.ollama.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@SpringBootApplication
public class ExerciseApplication {

    private static final String OLLAMA_BASE_URL = "http://localhost:11434";
    private static final String DEFAULT_MODEL = "qwen3:4b"; // 根据实际安装的模型调整

    public static void main(String[] args) {
        SpringApplication.run(ExerciseApplication.class, args);
    }

    /**
     * Spring Boot启动后执行的示例代码
     * 展示如何在Spring Boot应用中使用Ollama客户端
     */
    @Bean
    public CommandLineRunner ollamaDemo() {
        return args -> {
            System.out.println("\n=== Spring Boot中的Ollama Java原生HTTP客户端示例 ===");
            System.out.println("确保Ollama服务正在运行在: " + OLLAMA_BASE_URL);
            System.out.println("如果Ollama未运行，以下示例将显示连接错误\n");

            // 创建Ollama客户端
            OllamaClient client = new OllamaClient(OLLAMA_BASE_URL);

            try {
                // 1. 测试连接和获取模型列表
                testConnection(client);

                // 2. 简单的文本生成示例
                simpleGenerateExample(client);

                // 3. 异步调用示例
                asyncGenerateExample(client);

                // 4. 聊天接口示例
                chatExample(client);

                // 5. 错误处理示例
                errorHandlingExample(client);

            } catch (Exception e) {
                System.err.println("Ollama示例执行出错: " + e.getMessage());
                System.err.println("请确保:");
                System.err.println("1. Ollama服务正在运行 (ollama serve)");
                System.err.println("2. 已安装模型 (ollama pull " + DEFAULT_MODEL + ")");
                System.err.println("3. 服务地址正确: " + OLLAMA_BASE_URL);
            }

            System.out.println("\n=== 示例完成 ===");
            System.out.println("要运行完整的交互式示例，请执行: java -cp target/classes com.cyx.exercise.ollama.OllamaExample");
        };
    }

    /**
     * 测试连接和获取模型列表
     */
    private void testConnection(OllamaClient client) {
        System.out.println("1. 测试连接和获取模型列表...");
        try {
            String models = client.getModels();
            System.out.println("✓ 连接成功！可用模型: " + models.substring(0, Math.min(100, models.length())) + "...");
        } catch (Exception e) {
            System.err.println("✗ 连接失败: " + e.getMessage());
            throw new RuntimeException("无法连接到Ollama服务", e);
        }
        System.out.println();
    }

    /**
     * 简单的文本生成示例
     */
    private void simpleGenerateExample(OllamaClient client) {
        System.out.println("2. 简单文本生成示例...");
        try {
            OllamaRequest request = new OllamaRequest(DEFAULT_MODEL, "用一句话解释什么是Java");

            long startTime = System.currentTimeMillis();
            OllamaResponse response = client.generate(request);
            long endTime = System.currentTimeMillis();

            System.out.println("✓ 生成成功!");
            System.out.println("问题: " + request.getPrompt());
            System.out.println("回答: " + response.getResponse());
            System.out.println("耗时: " + (endTime - startTime) + "ms");
            System.out.println("状态: " + (response.isDone() ? "完成" : "未完成"));

        } catch (Exception e) {
            System.err.println("✗ 文本生成失败: " + e.getMessage());
        }
        System.out.println();
    }

    /**
     * 异步调用示例
     */
    private void asyncGenerateExample(OllamaClient client) {
        System.out.println("3. 异步调用示例...");
        try {
            OllamaRequest request = new OllamaRequest(DEFAULT_MODEL, "列举3个Java的优点");

            long startTime = System.currentTimeMillis();
            CompletableFuture<OllamaResponse> future = client.generateAsync(request);

            System.out.println("✓ 异步请求已发送，等待响应...");

            // 等待异步结果
            OllamaResponse response = future.get(); // 在实际应用中可以设置超时
            long endTime = System.currentTimeMillis();

            System.out.println("✓ 异步响应接收完成!");
            System.out.println("问题: " + request.getPrompt());
            System.out.println("回答: " + response.getResponse());
            System.out.println("异步耗时: " + (endTime - startTime) + "ms");

        } catch (Exception e) {
            System.err.println("✗ 异步调用失败: " + e.getMessage());
        }
        System.out.println();
    }

    /**
     * 聊天接口示例
     */
    private void chatExample(OllamaClient client) {
        System.out.println("4. 聊天接口示例...");
        try {
            OllamaChatRequest chatRequest = new OllamaChatRequest(DEFAULT_MODEL);

            // 设置系统提示
            chatRequest.addSystemMessage("你是一个专业的Java开发助手，请简洁地回答问题。");

            // 添加用户问题
            chatRequest.addUserMessage("Spring Boot的主要特点是什么？");

            OllamaChatResponse response = client.chat(chatRequest);

            System.out.println("✓ 聊天响应成功!");
            System.out.println("用户: Spring Boot的主要特点是什么？");
            System.out.println("助手: " + response.getMessage().getContent());
            System.out.println("角色: " + response.getMessage().getRole());

        } catch (Exception e) {
            System.err.println("✗ 聊天接口调用失败: " + e.getMessage());
        }
        System.out.println();
    }

    /**
     * 错误处理示例
     */
    private void errorHandlingExample(OllamaClient client) {
        System.out.println("5. 错误处理示例...");

        // 测试无效模型
        try {
            OllamaRequest invalidRequest = new OllamaRequest("invalid-model-name", "测试问题");
            client.generate(invalidRequest);
            System.out.println("✗ 预期应该失败，但成功了");
        } catch (IOException e) {
            System.out.println("✓ 正确捕获HTTP错误: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("✓ 正确捕获其他错误: " + e.getClass().getSimpleName() + " - " + e.getMessage());
        }

        // 测试空请求
        try {
            OllamaRequest emptyRequest = new OllamaRequest(DEFAULT_MODEL, "");
            OllamaResponse response = client.generate(emptyRequest);
            System.out.println("✓ 空请求处理: " + (response.getResponse().isEmpty() ? "返回空响应" : "返回了内容"));
        } catch (Exception e) {
            System.out.println("✓ 空请求错误处理: " + e.getMessage());
        }

        System.out.println();
    }
}
